package com.mezz.bones.framework.base.tree;

/**
 * @Author: zhuang
 * @Date: 2024/11/19 16:02
 * @Description: TODO
 * @Version: 1.0
 **/
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Data
public class TreeNode<Info> {
    private String id;
    private String parentId;
    private String name;
    
    /**
     * 节点层级，从0开始
     */
    private Integer level;
    
    /**
     * 父节点路径，格式：0,1,2,3
     * 最后一个是自身ID，0是根节点
     */
    private String parentIds;
    
    private final List<TreeNode<Info>> children = new ArrayList<>();

    /**
     * 节点附加信息
     */
    private Info info;

    public TreeNode(){}

    // 构造器 (无附加属性)
    public TreeNode(String id, String parentId, String name) {
        this.id = id;
        this.parentId = parentId;
        this.name = name;
        this.level = 1;
        this.parentIds = "0," + id;
    }

    public TreeNode(String id, String parentId, String name, Info info) {
        this.id = id;
        this.parentId = parentId;
        this.name = name;
        this.info = info;
        this.level = 1;  // 默认设置为0，需要在构建树时更新
        this.parentIds = "0";  // 默认设置为根节点，需要在构建树时更新
    }

    public void addChild(TreeNode<Info> child) {
        child.setLevel(this.level + 1);
        child.setParentIds(this.parentIds + "," + child.getId());
        this.children.add(child);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TreeNode<?> treeNode = (TreeNode<?>) o;
        return Objects.equals(id, treeNode.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}
